package com.lb.shopguide.util.lb;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Base64;

import com.blankj.utilcode.constant.RegexConstants;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.network.PageBean;
import com.lb.shopguide.ui.activity.GuideActivity;
import com.lb.shopguide.ui.dialog.DialogShare;
import com.lb.shopguide.ui.view.onekeyshare.OnekeyShare;
import com.lb.shopguide.util.FileUtilsExt;
import com.lb.shopguide.util.json.JsonUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.ShareSDK;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/4/25.
 * 全部是业务逻辑
 */

public class BizUtil {
    public static String[] MONTHS = new String[]{
            "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
    };
    private static Document doc;

    public static String getContentInBodyTag(String str) {
        String result = "";
        if (!TextUtils.isEmpty(str)) {
            doc = Jsoup.parse(str);
            Elements links = doc.getElementsByTag("body");
            if (links.size() != 0) {
                return getContentInTag(links);
            } else {
                return str;
            }
        } else {
            return result;
        }
    }

    private static String getContentInTag(Elements links) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < links.size(); i++) {//若干p标签
            Element element = links.get(i);
            if (!TextUtils.isEmpty(element.text())) {
                sb.append(element.html());
            } else {
                Element child = element.child(0);
                sb.append(child.outerHtml());
            }
        }
        return sb.toString();
    }


    public static PageBean getPageBeanFromJSONObject(JSONObject jsonObject) {
        PageBean pageBean = new PageBean();
        try {
            if (jsonObject.has("pageNum")) {
                pageBean.setPageNum(jsonObject.getInt("pageNum"));
            }
            if (jsonObject.has("pageSize")) {
                pageBean.setPageSize(jsonObject.getInt("pageSize"));
            }
            if (jsonObject.has("total")) {
                pageBean.setTotal(jsonObject.getInt("total"));
            }
            if (jsonObject.has("pages")) {
                pageBean.setTotal(jsonObject.getInt("pages"));
            }
            if (jsonObject.has("hasNextPage")) {
                pageBean.setHasNextPage(Boolean.parseBoolean(String.valueOf(jsonObject.getInt("hasNextPage"))));
            }
            if (jsonObject.has("list")) {
                pageBean.setList2(jsonObject.getJSONArray("list"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return pageBean;
    }

    public static boolean compareVersion(String remoteVersion, String localVersion) {
        String[] remoteVersions = fillVersion(remoteVersion).split("\\.");
        String[] localVersions = fillVersion(localVersion).split("\\.");
        if ((Integer.parseInt(remoteVersions[0]) > Integer.parseInt(localVersions[0]))) {
            return true;
        } else if ((Integer.parseInt(remoteVersions[0]) < Integer.parseInt(localVersions[0]))) {
            return false;
        } else {
            if (Integer.parseInt(remoteVersions[1]) > Integer.parseInt(localVersions[1])) {
                return true;
            } else if (Integer.parseInt(remoteVersions[1]) < Integer.parseInt(localVersions[1])) {
                return false;
            } else {
                return Integer.parseInt(remoteVersions[2]) > Integer.parseInt(localVersions[2]);
            }
        }
    }

    private static String fillVersion(String version) {
        if (version.length() == 3) {
            version = version + ".0";
        }
        return version;
    }

    public static String getRandomName(int digit) {
        StringBuffer sb = new StringBuffer(digit);
        for (int i = 0; i < digit; i++) {
            String word = Integer.toHexString(new Random().nextInt());
            sb.append(word);
        }
        return sb.toString();
    }

    public static Map getHeadersGet() {
        Map headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        String userToken = UserConfigManager.getInstance(GuideApplication.context()).getUserToken();
        //正常逻辑
        if (!TextUtils.isEmpty(userToken)) {
            LogUtils.d("Authorization====" + userToken);
            headers.put("Authorization", userToken);
        }

        return headers;
    }

    public static Map getHeadersPost() {
        Map headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        return headers;
    }

    public static void logout(Activity activity, UserConfigManager userConfigManager) {
        userConfigManager.setUserId("");
        userConfigManager.setUserToken("");
        userConfigManager.setAccId("");
        userConfigManager.setImToken("");
        userConfigManager.save2Sp(true);
        LogoutHelper.logout();
        JPushInterface.deleteAlias(activity, AppConstant.SEQUENCE_SET_ALIAS);
        JPushInterface.cleanTags(activity, AppConstant.SEQUENCE_CLEAN_TAGS);
        JPushInterface.setMobileNumber(activity, AppConstant.SEQUENCE_SET_MOBILENUMBER, "");
        activity.finish();
        Intent intent = new Intent(activity, GuideActivity.class);
        intent.putExtra(AppConstant.INTENT_KEY_FROM_LOGOUT, true);
        activity.startActivity(intent);
    }

    /**
     * 46是.符号
     *
     * @param str
     * @return
     */
    public static String getPureNumber(String str) {
        str = str.trim();
        String strRet = "";
        if (str != null && !"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if ((str.charAt(i) >= 48 && str.charAt(i) <= 57) || str.charAt(i) == 46) {
                    strRet += str.charAt(i);
                }
            }

        }
        return strRet;
    }


    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }


    public static void share(Context context, String title, String content, String url, String path, String platform, String check) {
        OnekeyShare oks = new OnekeyShare();
//关闭sso授权
        oks.disableSSOWhenAuthorize();

        oks.setPlatform(platform);
// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
//        oks.setTitle("标题");
        oks.setTitle(title);
// text是分享文本，所有平台都需要这个字段
//        oks.setText("我是分享文本");
        oks.setText(content);
// url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://sharesdk.cn");
        oks.setUrl(url);
        oks.setImagePath(path);

        oks.setSilent(false);
// 启动分享GUI
        oks.show(context);
    }

    public static void share(Context context, String title, String content, String url, String imgUrl, String platform) {
        OnekeyShare oks = new OnekeyShare();
//关闭sso授权
        oks.disableSSOWhenAuthorize();

        oks.setPlatform(platform);
// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
//        oks.setTitle("标题");
        oks.setTitle(title);
// text是分享文本，所有平台都需要这个字段
//        oks.setText("我是分享文本");
        oks.setText(content);
// url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://sharesdk.cn");
        oks.setUrl(url);
        if (TextUtils.isEmpty(imgUrl)) {
            AssetManager assetManager = context.getAssets();
            InputStream is = null;
            try {
                is = assetManager.open("logo.png");
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                String path = FileUtilsExt.saveBitmap(bitmap);
                oks.setImagePath(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            oks.setImageUrl(imgUrl);
        }

        oks.setSilent(false);
// 启动分享GUI
        oks.show(context);
    }

    public static DialogShare showShareDialog(FragmentManager manager, String shareUrl) {
        DialogShare dialogShare = null;
        if (!TextUtils.isEmpty(shareUrl)) {
            dialogShare = DialogShare.getDialogShare();
            dialogShare.show(manager, "dialogShare");
        } else {
            ToastUtils.showShort("暂无可分享的内容");
            return null;
        }
        return dialogShare;
    }

    public static String getNumberWithStars(String phoneNumber) {
        return phoneNumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    public static boolean isDoubleOrFloat(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();
    }


    public static String convertBigNumber(String num, Integer digit) {
        float fNum = Float.parseFloat(num);
        if (fNum < 10000) {
            return "" + num;
        }
        String unit = "万";
        double newNum = fNum / 10000.0;
        if (digit != null) {
            String numStr = String.format("%." + digit + "f", newNum);
            return numStr + unit;
        }
        return newNum + unit;
    }

    public static RequestBody getBodyFromMap(HashMap hashMap) {
        String strEntity = JsonUtil.getGson().toJson(hashMap);
        return RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
    }


    /**
     * Return whether input matches regex of username.
     * <p>scope for "a-z", "A-Z", "0-9", "_", "Chinese character"</p>
     * <p>can't end with "_"</p>
     * <p>length is between 6 to 20</p>.
     *
     * @param input The input.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isUsername(final CharSequence input) {
        return isMatch(REGEX_USERNAME, input);
    }

    private static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{1,20}(?<!_)$";

    /**
     * Return whether input matches the regex.
     *
     * @param regex The regex.
     * @param input The input.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isMatch(final String regex, final CharSequence input) {
        return input != null && input.length() > 0 && Pattern.matches(regex, input);
    }

    public static Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray = Base64.decode(string.split(",")[1], Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 清除WebView缓存
     */
    public static void clearWebViewCache(Context context) {
        context.deleteDatabase("webview.db");
        context.deleteDatabase("webviewCache.db");
    }

    public static Bitmap getBitmap(String imgUrl) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        URL url = null;
        try {
            url = new URL(imgUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setReadTimeout(2000);
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() == 200) { //网络连接成功
                inputStream = httpURLConnection.getInputStream();
                outputStream = new ByteArrayOutputStream();
                byte buffer[] = new byte[1024 * 8];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                byte[] bu = outputStream.toByteArray();
                Bitmap bitmap = BitmapFactory.decodeByteArray(bu, 0, bu.length);
                return bitmap;
            } else {
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) { // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) { // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 通过URL地址获取Bitmap对象 * @Title: getBitMapByUrl * @param @param url * @param @return * @param @throws Exception * @return Bitmap * @throws
     */
    public static Bitmap getBitmapByUrl(final String url) {
        URL fileUrl = null;
        InputStream is = null;
        Bitmap bitmap = null;
        try {
            fileUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            is = null;
        }
        return bitmap;
    }

    /**
     * 跳转到微信
     */
    public static void jumpToWechat(Context context) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtils.showLong("检查到您手机没有安装微信，请安装后使用该功能");
        }
    }


    public static boolean copyToClipboard(Context context, String copyString) {
        if (context == null) {
            return false;
        }
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText(null, copyString);
        if (cm != null) {
            cm.setPrimaryClip(mClipData);
            return true;
        }
        return false;
    }

    public static String fixActivityUrl(String url, String code) {
        String returnUrl;
        if (!url.contains("token")) {
            if (url.contains("?")) {
                returnUrl = url + "&token=" + UserConfigManager.getInstance(GuideApplication.context()).getUserToken() + "&type=android" + "&xd_code=" + code;
            } else {
                returnUrl = url + "?token=" + UserConfigManager.getInstance(GuideApplication.context()).getUserToken() + "&type=android" + "&xd_code=" + code;
            }
        } else {
            return url;
        }
        return returnUrl;
    }

    public static String formatDuring(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        if (days == 0) {
            return hours + " 小时 ";
        } else {
            return days + " 天 " + hours + " 小时 ";
        }
    }

    /**
     * 七牛 图片压缩
     *
     * @return
     */
    public static String addSlimParam(String url) {
        if (url.contains("?")) {
            return url.concat("&imageslim");
        } else {
            return url.concat("?imageslim");
        }
    }

}
